package CExtends {
	import UIFree.ObjectEvent;
	
	import flash.events.Event;
	import flash.events.MouseEvent;
	import flash.events.ProgressEvent;
	import flash.geom.Rectangle;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.net.URLRequest;
	
	public class pie_upload extends Object {
		protected var BUTTONTITLE: String = '';
		
		private var _app: Object;
		private var _button: Object;
		private var _loader: Object;
		private var _fref: FileReference;
		private var _request: URLRequest;
		private var _fileName: String;
		private var _extendsLayer: Object;
		
		public function pie_upload(a_app: Object, extendsLayer: Object) {
			super();
			_extendsLayer = extendsLayer;
			_app = a_app;
			_fref = new FileReference();
        	_fref.addEventListener(Event.OPEN, doOpenHandler); 
        	_fref.addEventListener(ProgressEvent.PROGRESS, doProgress);
        	_fref.addEventListener(Event.COMPLETE, doCompleteHandler);
            _fref.addEventListener(Event.SELECT, doSelectHandler);

			createUserInterface();
		}
		
		protected function createUserInterface(): void {
			_button = _app.extendsLayer.getExtButton('extends');
			_button.addEvent(MouseEvent.CLICK, doShowDialog);
			BUTTONTITLE = _button.text;
			var inner: Rectangle = _button.getInner();
			_loader = new _app.classes['loaderBar'](_button, inner.x, inner.y, inner.width, inner.height, 'loaderBar');
			_loader.visible = false;
		}
		
		protected function doSelectHandler(e: Event): void {
			_fref.load();
		}
		
		protected function doOpenHandler(e: Event): void {
			_loader.slideShow();
			_button.text = '';
		}
		
		protected function doProgress(e: ProgressEvent): void {
			_loader.percent = e.bytesLoaded / e.bytesTotal * 100;
		}
		
		protected function doCompleteHandler(e: Event): void {
			_loader.slideHide();
			_button.text = BUTTONTITLE;
			_request = null;
			_app.photo.loadBytes(_fref.data);
		}
		
		protected function doShowDialog(e: Event): void {
			if (!_request) {
				_fref.browse([new FileFilter('JPEG формат', '*.jpg'),
								new FileFilter('PNG формат', '*.png'),
								new FileFilter('GIF формат', '*.gif'),
								new FileFilter('Любые файлы', '*.*')]);
			}
		}
	}
}